
<?php 
	
	class Agent_model extends CI_Model {
		
		 var $tblName = "qagent";
		 
		function __construct()
		{
			parent::__construct();
		}
		
		function save_skill_priority($POST)
		{
			$uniqueids = $POST['ids'];
			$primary_skill = $POST['primary_skill'][0];
			
			if( count($uniqueids) > 0 ) 
			{
				foreach($uniqueids as $id)
				{
					$record = array( 
										'penalty' 		=> intval($POST['penalty'][$id]),
										'primary_skill' => addslashes($primary_skill)
									);
					$this->db->where('uniqueid', $id);				
					$this->db->update("queue_member_table", $record);
				}//end foreach 
			}
		}
		
		function save_agent_skills($POST)
		{
			$agent = $POST['agent'];
			$agent = "Agent/".$agent;
	
			$skills			= @$POST['skills'];
			$primary_skill 	= @$POST['primary_skill'];
			$primary_skill = $primary_skill[0];
  			
			if( count($skills) > 0 ) 
			{
				//____________________ delete other skill _____________________
				$sql_delete = " DELETE from queue_member_table where membername = ".$this->db->escape($agent)."";		
				$this->db->query($sql_delete);			
				
				foreach($skills as $skill)
				{
					$record = array(
										'membername' 	=> addslashes($agent),
										'queue_name' 	=> addslashes($skill),
										'interface' 	=> addslashes($agent),
										'penalty' 		=> intval($POST['priority'][$skill]),
										'callerid' 		=> addslashes($POST['callerid'][$skill]),
										'queue_callerid'=> addslashes($POST['queue_callerid'][$skill]),
										'primary_skill' => addslashes($primary_skill)
									);
									
					$this->db->insert("queue_member_table", $record);
				}//end foreach 
			}
		}//end function
		
		function getAgentSkills($membername)
		{
			$sql = "SELECT * FROM `queue_member_table` WHERE `membername` LIKE '".mysql_real_escape_string($membername)."' order by primary_skill, queue_name";
			return $this->db->query($sql)->result(); 			
		}
		
		function getDetailByID($id)
		{
		  $id = (int)$id;	
		  $sql = "SELECT
				q.agent_id,
				s.name as agent,
				s.username,
				s.secret,
				s.context,
				s.allow,
				q.First_Name,
				q.Last_Name,
				q.location_name
			FROM
				qagent q,
				sip_buddies s
			WHERE
				SUBSTRING_INDEX(q.agent, '/', - 1) = s. NAME
			AND q.agent_id = ".$id;
		  return $this->db->query($sql)->row_array();
		}
		

		function getListingData($GET, $start, $offset = 20)
		{
 			$where = ' WHERE 1=1 ';
			if( isset($GET['agent']) && trim($GET['agent']) != '' )
			{
				$where  .= " AND agent LIKE '%".trim($this->db->escape($GET['agent']),"'")."%' ";	
			}
			if( isset($GET['name']) && trim($GET['name']) != '' )
			{
				$where  .= " AND concat(First_name, ' ', Last_name) LIKE '%".trim($this->db->escape($GET['name']),"'")."%' ";	
			}
			
			$LIMIT = "LIMIT $start ,  $offset ";
			$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM " . $this->tblName . " {$where} order by first_name {$LIMIT} ";
			$results = $this->db->query($sql)->result();	
			$total_record = $this->common_model->get_found_rows();
			
			return array('results' => $results, 'total_record' => $total_record);
		}
		
		function getAgentPrimarySkill($membername)
		{
			$sql = "SELECT * FROM `queue_member_table` WHERE `membername` LIKE '".mysql_real_escape_string($membername)."'";
			$result = $this->db->query($sql)->row_array(); 			
			if( isset($result['primary_skill']) ) {
				return $result['primary_skill'];	
			} else {
				return '';	
			}
		}
		
		function getAllagent()
		{
			$sql = "select *, concat(First_Name, ' ', Last_Name) as agent_name from qagent ";
			return $this->db->query($sql)->result();
		}
		
		function updateSIPConfigFile($agent_data, $sip_file_path, $action="add")
		{
			vardump($agent_data);
			
			$extension 	= $agent_data['agent'];
			$secret 	=  $agent_data['secret'];
			$type		= "friend";
			$host		= "host";
			$nat		= "no";
			$qualify	= "5000";
			$context	= $agent_data['context'];
			
			$found = false;
			$file_content = file($sip_file_path);
			
			if( ! $file_content && ! is_array( $file_content )  ) {
				echo "Unable to read file : SIP.Conf";
				exit;
			}
			
			$line_no = 0;
			$end = 0;
			if( count($file_content) > 0 )
			{				 
				foreach($file_content as $line ) 
				{
					$line_no++;
					if( preg_match("/\[$extension\]/", $line, $matches) )
					{
						$start = $line_no;
						$found = true;
					
					}
					elseif( preg_match("/\[[0-9]+\]/", $line, $matches) && $found)
					{
						$end = $line_no-1;	
						break;
					} 
					//$line_no++;
				}
			}
			
			echo "start: $start <br> end : $end ";
			exit;
 				
			if( $found ) // if entry found in file, update content
			{
				$file_content[$start] = "[{$extension}]";
				$file_content[$start+1] = "\n\tusername={$extension}";
				$file_content[$start+2] = "\n\tsecret={$secret}";
				$file_content[$start+3] = "\n\ttype={$type}";
				$file_content[$start+4] = "\n\thost={$host}";
				$file_content[$start+5] = "\n\tnat={$nat}";
				$file_content[$start+6] = "\n\tqualify={$qualify}";
				$file_content[$start+7] = "\n\tcontext={$context}\n";
			}
			else	// add new entry
			{
				$file_content[] = "\n[{$extension}]";
				$file_content[] = "\n\tusername={$extension}";
				$file_content[] = "\n\tsecret={$secret}";
				$file_content[] = "\n\ttype={$type}";
				$file_content[] = "\n\thost={$host}";
				$file_content[] = "\n\tnat={$nat}";
				$file_content[] = "\n\tqualify={$qualify}";
				$file_content[] = "\n\tcontext={$context}\n";	
			}
				
			if( ! file_put_contents($sip_file_path, implode('',$file_content)) ) {
				echo "Unable to write file : SIP.Conf";
				exit;	
			}
		}
		
		function updateAgentConfigFile($agent_data, $agent_file_path, $action)
		{
			$extension 	= $agent_data['agent'];
			$secret 	= $agent_data['secret'];
			$str_agent = "agent => $extension,$secret";										
			
			// open file for read
			$fh = fopen($agent_file_path, "r");
			if ($fh === false)
			{
				echo "Unable to open file for reading : agent.conf";
				exit;
			}
			$str = fread($fh, filesize($agent_file_path));
			fclose($fh);
			// end open file for read
			
			$matches = array();
			$pattern = "/agent\s*=>\s*$extension,\s*$secret/";
			if (preg_match($pattern, $str, $matches))	// if entry found then update 
			{
				$str = preg_replace($pattern, $str_agent, $str);
				
			}
			else // add new entry
			{
				if( strlen($str) > 0 ) {		// if we entry is already there, then start with end line
					$str .= "\n".$str_agent;
				} else {	// if it is going to be first entry no need to put it in new line
					$str .= $str_agent;
				}
			}
			
			
			// open file for writing
			$fh = fopen($agent_file_path, "w");
			if($fh === false)
			{
				echo "Unable to open file for writing : agent.conf";
				exit;
			}
			
			if(!fwrite($fh, $str, strlen($str)))
			{
				echo "Unable to write file : agent.conf";
				exit;
			}
			
			fflush($fh);
			fclose($fh);
			
			
		}
		
		
		function updateConfigFile($agent_id, $action="add")
		{
			$agent_data = $this->getDetailByID($agent_id);
 
  			$sip_file = $this->sip_file_path;
			$agent_file = $this->agent_file_path;
			
			$this->updateSIPConfigFile($agent_data, $sip_file, $action);
			$this->updateAgentConfigFile($agent_data, $agent_file, $action);
		}
		
  }
?>